class Article {
  String title;
  String author;
  String description;
  String urlToImage;
  DateTime publishedAt;
  String content;
  String articleUrl;

  Article(
      {required String? title,
      required String? description,
      required String? author,
      required String? content,
      required String? publishedAt,
      required String? urlToImage,
      required String? articleUrl})
      : this.title = title ?? '无标题',
        this.description = description ?? '暂无描述',
        this.author = author ?? '未知作者',
        this.content = content ?? '暂无内容',
        this.publishedAt =
            publishedAt != null ? DateTime.parse(publishedAt) : DateTime.now(),
        this.urlToImage = _validateImageUrl(urlToImage),
        this.articleUrl = articleUrl ?? '';

  static String _validateImageUrl(String? url) {
    // 使用本地资源作为占位图
    const String defaultImage = 'assets/images/no_image.png';
    const String invalidUrlImage = 'assets/images/invalid_url.png';
    const String unsupportedFormatImage = 'assets/images/unsupported_format.png';
    const String fallbackImage = 'assets/images/fallback.png';

    // 空值检查
    if (url == null || url.isEmpty) {
      return fallbackImage;
    }

    // URL格式验证
    try {
      final uri = Uri.parse(url);
      
      // 检查是否是HTTP/HTTPS协议
      if (!uri.scheme.startsWith('http')) {
        return invalidUrlImage;
      }

      // 检查文件扩展名和域名
      final extension = uri.path.toLowerCase();
      final host = uri.host.toLowerCase();
      if (!extension.endsWith('.jpg') && 
          !extension.endsWith('.jpeg') && 
          !extension.endsWith('.png') && 
          !extension.endsWith('.gif') && 
          !extension.endsWith('.webp')) {
        return unsupportedFormatImage;
      }

      // 检查是否是已知的有访问限制的域名
      if (host.contains('thedailybeast.com') || 
          host.contains('restricted-domain.com')) {
        return fallbackImage;
      }

      // 如果所有检查都通过，返回原始URL
      return url;
    } catch (e) {
      return invalidUrlImage;
    }
  }

  @override
  String toString() {
    return 'Article{title: $title, author: $author, publishedAt: $publishedAt}';
  }
}
